﻿function BuildHeader()
{
	if (_page == 'vote_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&IsRecycled=' + $('#IsRecycled').val() + '&Sort=' + $('#Sort').val() + '&Keyword=' + encodeURIComponent($('#Keyword').val()) + '&KeywordType=' + $('#KeywordType').val() + '&Page=' + _pageNumber;
	else
	    return BuildAjaxPath();
}

function Search()
{
	if (arguments.length > 0 && typeof(arguments[0]) != 'object')
		_pageNumber = arguments[0];
	
	SetStatusMessage(_lang_working);

	$.ajax(
	{
		url: BuildHeader(),
		data: {},
		type: 'POST',
		error: function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success: function(data)
		{
			var list = $('#List');

			list.html(HandleFake404(data, 'text'));
			SetStatusMessage();

			if (typeof(SetupIme) == 'function')
				SetupIme();
				
			MakeButton();
		}
	});
}

function MakeButton()
{
	var buttons = '';
	var button;
	
	//回收
	button = $('#IsRecycled');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
	    {
		    buttons += '<button class="Button" id="Recycle">' + _lang_recycle + '</button>';
	    }
	    else if (button[0].selectedIndex == 2)
	    {
		    buttons += '<button class="Button" id="Delete">' + _lang_delete + '</button>';
		    buttons += '<button class="Button" id="Recover">' + _lang_recover + '</button>';
	    }
	}

	$('#ExtraButton').html(buttons);
}

//-------------------------------------------------
//Start : 投票
function Vote()
{
	var __object = 'Vote',
		__base = new Base(),
		__optionIndex,
		__options = [];

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (this.TimeLimitForSameUser.value != '' && !this.TimeLimitForSameUser.value.match(/^\d+$/))
		{
			Alert(_lang_time_limit_for_same_user_incorrect, function(){this.TimeLimitForSameUser.select();}, this);
			return false;
		}
		
		var optionsRows = $('#options-table tbody tr[id!=option-edit]');
		if (optionsRows.length == 0)
		{
			Alert(_lang_select_option);
			return false;
		}
		
		//选项列表
		__optionIndex = 0;
		__options.length = 0;
		for (var i = 0; i < optionsRows.length; i++)
		{
			var text = $('td:eq(0) input', optionsRows.eq(i));
			var name = text.val();
			if (name == '')
			{
				Alert(_lang_name_empty, function(){text[0].select();}, this);
				return false;
			}

			var uploadForm = 'picture' + i;
			var needUpload = _uploader.NeedUpload(uploadForm);
			var picture;
			if (!needUpload)
				picture = $('td:eq(1) :text', optionsRows.eq(i)).val();
			__options.push({name:name,uploadForm:uploadForm,needUpload:needUpload,content:optionsRows.eq(i).data('content'),picture:picture});
		}

		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&IsSingle=' + $('#IsSingleYes')[0].checked;
		if (this.Unit.value == 'Minute')
			data += '&TimeLimitForSameUser=' + this.TimeLimitForSameUser.value;
		else if (this.Unit.value == 'Hour')
			data += '&TimeLimitForSameUser=' + parseInt(this.TimeLimitForSameUser.value) * 60;
		else if (this.Unit.value == 'Day')
			data += '&TimeLimitForSameUser=' + parseInt(this.TimeLimitForSameUser.value) * 60 * 24;

		data += '&Description=' + encodeURIComponent(CKEDITOR.instances[this.Description.id].getData());
		
		__base.add({object:__object,data:data,onSuccess:function(data){addOption(data);}});

		return false;
	};
	
	this.initOption = function()
	{
		__optionIndex = 0;
		__options.length = 0;
		$('#options-table tbody tr[id!=option-edit]').each(function(i)
		{
			var text = $('td:eq(0) input', this);
			var name = text.val();
			if (name == '')
				return false;

			var uploadForm = 'picture' + i;
			var needUpload = _uploader.NeedUpload(uploadForm);
			var picture;
			if (!needUpload)
				picture = $('td:eq(1) :text', this).val();
			__options.push({id:$(this).data('id'),name:name,uploadForm:uploadForm,needUpload:needUpload,content:$(this).data('content'),picture:picture,sort:i});
			_uploader.Add(uploadForm, 'picture' + i + '-textbox', 'picture' + i + '-browse');
		});
	}
	
	function addOption(voteId)
	{
		if (__optionIndex >= __options.length)
		{
			Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
			
			return;
		}
		
		var data = 'VoteID=' + voteId;
		data += '&Name=' + encodeURIComponent(__options[__optionIndex].name);
		if (!__options[__optionIndex].needUpload)
			data += '&Picture=' + __options[__optionIndex].picture;
		data += '&Content=' + encodeURIComponent(__options[__optionIndex].content);
		data += '&Sort=' + __optionIndex;
		
		var guid = __base.add({object:'Vote.Option',operation:'Add',data:data,silent:true});
		var id = __base.post({object:'Vote.Option',operation:'GetInnerIDFromGuid',params:'ID=' + guid});

		//上传图片
		if (__options[__optionIndex].needUpload)
		{
			SetStatusMessage(_lang_start_upload);
			_uploader.Init({Status:_lang_uploading,Params:'Lang=' + _lang + '&Object=Vote.Option&Operation=UploadPicture&ID=' + id});
			_uploader.Upload(__options[__optionIndex].uploadForm, function()
			{
				if (arguments[0] != 0)
				{
					SetStatusMessage();
					$(':submit')[0].disabled = false;
				}
				else
				{
					__optionIndex++;
					addOption(voteId);
				}
			});
		}
		else
		{
			__optionIndex++;
			addOption(voteId);
		}
	}
	
	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (this.TimeLimitForSameUser.value != '' && !this.TimeLimitForSameUser.value.match(/^\d+$/))
		{
			Alert(_lang_time_limit_for_same_user_incorrect, function(){this.TimeLimitForSameUser.select();}, this);
			return false;
		}
		
		var optionsRows = $('#options-table tbody tr[id!=option-edit]');
		if (optionsRows.length == 0)
		{
			Alert(_lang_select_option);
			return false;
		}
		
		//选项列表
		var options = __options;
		__optionIndex = 0;
		__options = [];
		for (var i = 0; i < optionsRows.length; i++)
		{
			var text = $('td:eq(0) input', optionsRows.eq(i));
			var name = text.val();
			if (name == '')
			{
				Alert(_lang_name_empty, function(){text[0].select();}, this);
				return false;
			}
			
			var id = optionsRows.eq(i).data('id');
			if (!id) id = '';

			var uploadForm = 'picture' + i;
			var needUpload = _uploader.NeedUpload(uploadForm);
			var picture = $('td:eq(1) :text', optionsRows.eq(i)).val();
			var content = optionsRows.eq(i).data('content');
			
			var operation = null;
			if (id == '')
			{
				operation = 'Add';
			}
			else
			{
				var j = 0;
				for (; j < options.length; j++)
				{
					if (id == options[j].id && (name != options[j].name || picture != options[j].picture || content != options[j].content || i != options[j].sort))
						break;
				}
				
				if (j < options.length)
					operation = 'Modify';
			}

			__options.push({id:id,operation:operation,name:name,uploadForm:uploadForm,needUpload:needUpload,picture:picture,content:content});
		}
	
		for (var i = 0; i < options.length; i++)
		{
			var rows = $('#options-table tbody tr[data-id=' + options[i].id + ']');
			if (rows.length == 0)
			{
				options[i].operation = 'Delete';
				__options.push(options[i]);
			}
		}

		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&IsSingle=' + $('#IsSingleYes')[0].checked;
		if (this.Unit.value == 'Minute')
			data += '&TimeLimitForSameUser=' + this.TimeLimitForSameUser.value;
		else if (this.Unit.value == 'Hour')
			data += '&TimeLimitForSameUser=' + parseInt(this.TimeLimitForSameUser.value) * 60;
		else if (this.Unit.value == 'Day')
			data += '&TimeLimitForSameUser=' + parseInt(this.TimeLimitForSameUser.value) * 60 * 24;

		data += '&Description=' + encodeURIComponent(CKEDITOR.instances[this.Description.id].getData());
		
		__base.modify({object:__object,data:data,onSuccess:setOption});

		return false;
	};
	
	function setOption()
	{
		if (__optionIndex >= __options.length)
		{
			for (var i = __options.length - 1; i >= 0; i--)
			{
				if (__options[i].operation == 'Delete')
					__options.splice(i, 1);
			}
			
			Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
			return;
		}
		
		var operation;
		var params = null;
		var data;
		if (__options[__optionIndex].operation == null)
		{
			__optionIndex++;
			setOption();
			return;
		}
		else if (__options[__optionIndex].operation == 'Add')
		{
			var data = 'VoteID=' + _guid;
			data += '&Name=' + encodeURIComponent(__options[__optionIndex].name);
			if (!__options[__optionIndex].needUpload)
				data += '&Picture=' + __options[__optionIndex].picture;
			data += '&Content=' + encodeURIComponent(__options[__optionIndex].content);
			data += '&Sort=' + __optionIndex;
			
			var guid = __base.add({object:'Vote.Option',operation:'Add',data:data,silent:true});
			var id = __base.post({object:'Vote.Option',operation:'GetInnerIDFromGuid',params:'ID=' + guid});

			__options[__optionIndex].id = id;
			__options[__optionIndex].sort = __optionIndex;
	
			//上传图片
			if (__options[__optionIndex].needUpload)
			{
				SetStatusMessage(_lang_start_upload);
				_uploader.Init({Status:_lang_uploading,Params:'Lang=' + _lang + '&Object=Vote.Option&Operation=UploadPicture&ID=' + id});
				_uploader.Upload(__options[__optionIndex].uploadForm, function()
				{
					if (arguments[0] != 0)
					{
						SetStatusMessage();
						$(':submit')[0].disabled = false;
					}
					else
					{
						__optionIndex++;
						setOption();
					}
				});
			}
			else
			{
				__optionIndex++;
				setOption();
			}
		}
		else if (__options[__optionIndex].operation == 'Modify')
		{
			var data = 'Name=' + encodeURIComponent(__options[__optionIndex].name);
			if (!__options[__optionIndex].needUpload)
				data += '&Picture=' + __options[__optionIndex].picture;
			data += '&Content=' + encodeURIComponent(__options[__optionIndex].content);
			data += '&Sort=' + __optionIndex;
			
			__base.modify({object:'Vote.Option',id:__options[__optionIndex].id,data:data});
	
			//上传图片
			if (__options[__optionIndex].needUpload)
			{
				SetStatusMessage(_lang_start_upload);
				_uploader.Init({Status:_lang_uploading,Params:'Lang=' + _lang + '&Object=Vote.Option&Operation=UploadPicture&ID=' + __options[_productIndex].id});
				_uploader.Upload(__options[__optionIndex].uploadForm, function()
				{
					if (arguments[0] != 0)
					{
						SetStatusMessage();
						$(':submit')[0].disabled = false;
					}
					else
					{
						__optionIndex++;
						setOption();
					}
				});
			}
			else
			{
				__optionIndex++;
				setOption();
			}
		}
		else if (__options[__optionIndex].operation == 'Delete')
		{
			__base.post({object:'Vote.Option',operation:__options[__optionIndex].operation,data:{},onSuccess:setOption,params:'ID=' + __options[__optionIndex++].id});
		}
	}
	
	this.update = function(operation, id)
	{
		if (this.tagName == 'BUTTON')
			operation = this.id;

		__base.update(__object, operation, id);
	};
	
	this.addRow = function()
	{
		var optionsBody = $('#options-table tbody'),
			id = $('tr[id!=option-edit]', optionsBody).length,
			html = '<tr data-content=""><td><input type="text" size="40" class="Text ' + _lang + 'Font"' + (_lang == 'UYG' ? ' onkeydown="OnEdit()" onkeypress="OnEdit()"' : '') + '><button type="button">...</button></td><td><input id="picture' + id + '-textbox" type="text" class="Text"><input id="picture' + id + '-browse" type="button" value="' + _lang_browse + '"></td><td><button type="button" data-action="MoveUp">' + _lang_move_up + '</button><button type="button" data-action="MoveDown">' + _lang_move_down + '</button></td><td><button type="button" data-action="Delete">' + _lang_delete + '</button></td></tr>';
		
		optionsBody.append(html);
		_uploader.Add('picture' + id, 'picture' + id + '-textbox', 'picture' + id + '-browse');
	};
	
	this.moveUpRow = function()
	{
		var tr = $(this).closest('tr'),
			prev = tr.prev('[id!=option-edit]');
		
		if (prev.length)
			prev.before(tr);
	};
	
	this.moveDownRow = function()
	{
		var tr = $(this).closest('tr'),
			next = tr.next('[id!=option-edit]');
		
		if (next.length)
			next.after(tr);
	};
	
	this.deleteRow = function()
	{
		$(this).closest('tr').remove();
	};
	
	this.toggleContent = function(e)
	{
		var editRow = $('#option-edit');
		var cur = $(this).closest('tr');
		if (cur.next().index(editRow) == -1)
			editRow.insertAfter(cur).show();
		else
			editRow.toggle();
		
		if (editRow.is(':visible'))
			$('textarea', editRow).val(cur.data('content'));
	};
	
	this.onContentChanged = function()
	{
		$(this).closest('tr').prev().data('content', this.value);
	};
}
//End: 投票
//-------------------------------------------------

(function()
{
	if (typeof(_page) == 'undefined')
		return;
	
	if (_page == 'vote_add')
	{
		var vote = new Vote();
		
		$('form:first').submit(vote.add);
		$('#option-add').click(vote.addRow);
		$('#option-edit textarea').blur(vote.onContentChanged);
		$('#options-table').on('click', '[data-action=MoveUp]', vote.moveUpRow)
							.on('click', '[data-action=MoveDown]', vote.moveDownRow)
							.on('click', '[data-action=Delete]', vote.deleteRow)
							.on('click', 'td:nth-child(1) :button', vote.toggleContent);
	}
	else if (_page == 'vote_edit')
	{
		var vote = new Vote();
		
		var t = $('[name=TimeLimitForSameUser]').val();
		if (t != '')
		{
			t = parseInt(t);
			if (t % (60 * 24) == 0)
			{
				$('[name=Unit]').val('Day');
				$('[name=TimeLimitForSameUser]').val(t / (60 * 24));
			}
			else if (t % 60 == 0)
			{
				$('[name=Unit]').val('Hour');
				$('[name=TimeLimitForSameUser]').val(t / 60);
			}
			else
			{
				$('[name=Unit]').val('Minute');
			}
		}
		
		vote.initOption();
		
		$('form:first').submit(vote.modify);
		$('#option-add').click(vote.addRow);
		$('#option-edit textarea').blur(vote.onContentChanged);
		$('#options-table').on('click', '[data-action=MoveUp]', vote.moveUpRow)
							.on('click', '[data-action=MoveDown]', vote.moveDownRow)
							.on('click', '[data-action=Delete]', vote.deleteRow)
							.on('click', 'td:nth-child(1) :button', vote.toggleContent);
	}
	else if (_page == 'vote_list')
	{
		var vote = new Vote();
		
		MakeButton();

		$('#IsRecycled,#Sort').change(Search);
		$('body').on('click', '#Recycle,#Delete,#Recover', vote.update);
		$('#Keyword').keydown(function(e){if(e.keyCode == 13){Search(1);e.preventDefault();}});
		$('#Search').click(function(){Search(1);});
		$('#SelectAll').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = true;});});
		$('#ReverseSelect').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = !this.checked;});});
	}
})();